package at.codebase.web.servlets.ajax;

import java.util.ArrayList;

import org.json.simple.JSONObject;

import at.codebase.core.searchUser.UsernameSearch;
import at.codebase.core.searchUser.UsernameSearchResult;
import at.codebase.security.SecurityUtils;
import at.codebase.web.util.LocalRequest.RequestInformation;
import at.codebase.web.util.URLParameters.ParameterDoesNotExistException;
import at.codebase.web.util.servlet.SecureServlet;

import com.google.appengine.labs.repackaged.org.json.JSONArray;

/**
 * 
 * @author Lukas Pfeifhofer <lukas.pfeifhofer@devlabs.pro>
 *
 */
public class AjaxUsernameSearchProvider extends SecureServlet {

	private final static int MAX_RESULTS = 10;

	@Override
	protected RequestType requestType() {
		return RequestType.POST_AND_GET;
	}
	
	@Override
	protected void initSecurityLevels(ArrayList<UserLevel> secLevels) {
		secLevels.add(UserLevel.REGISTERED);
		secLevels.add(UserLevel.ADMIN);
	}

	@SuppressWarnings("unchecked")
	@Override
	protected void processRequestSecurityLevel(RequestInformation requestInfo, UserLevel level, RequestType requestType) {
		String query = "";
		String type = "";
		try {
			query = requestInfo.getParameters().getString("term");
		} catch (ParameterDoesNotExistException e) { }
		
		try {
			type = requestInfo.getParameters().getString("type");
		} catch (ParameterDoesNotExistException e) { }		
		

		ArrayList<UsernameSearchResult> resultList = UsernameSearch.search(query, MAX_RESULTS, 0);
		
		JSONArray jsonList = new JSONArray();
		
		for(UsernameSearchResult result:resultList){
			JSONObject resultJsonObject = new JSONObject();
			resultJsonObject.put("id", result.getId().toString());
			resultJsonObject.put("label", SecurityUtils.sanatize(result.getUsername()));
			if(type != null && type.equals("all")){
				jsonList.put(resultJsonObject);
			}else{
				if(!(requestInfo.isUserLoggedIn() && result.getId().equals(requestInfo.getUser().getId())))
					jsonList.put(resultJsonObject);	
			}
			
			
			
		}
		
		writer().printInsecure(jsonList.toString());
		
	}

}
